package io.gitee.welson.sensitive.converter;

import com.alibaba.excel.converters.string.StringStringConverter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import io.gitee.welson.sensitive.annotation.SensitiveField;
import io.gitee.welson.sensitive.condition.ConditionEvaluator;
import io.gitee.welson.sensitive.config.SensitiveExportProperties;
import io.gitee.welson.sensitive.strategy.SensitiveStrategy;
import io.gitee.welson.sensitive.strategy.SensitiveStrategyFactory;
import io.gitee.welson.sensitive.util.SensitiveContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;

/**
 * 字符串类型敏感数据转换器
 *
 * @author welson
 */
@Component
public class StringSensitiveConverter extends StringStringConverter {
    private final SensitiveStrategyFactory strategyFactory;
    private final SensitiveExportProperties properties;
    private final ConditionEvaluator conditionEvaluator;

    public StringSensitiveConverter(SensitiveStrategyFactory strategyFactory,
                                    SensitiveExportProperties properties,
                                    ConditionEvaluator conditionEvaluator) {
        this.strategyFactory = strategyFactory;
        this.properties = properties;
        this.conditionEvaluator = conditionEvaluator;
    }

    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (value != null && !value.isEmpty() && SensitiveContext.needDesensitize()) {
            Field field = contentProperty.getField();
            SensitiveField annotation = field.getAnnotation(SensitiveField.class);
            if (annotation != null) {
                return new WriteCellData<>(convert(value, annotation));
            }
        }
        return super.convertToExcelData(value, contentProperty, globalConfiguration);
    }

    public String convert(String value, SensitiveField annotation) {
        // 如果值为空，直接返回
        if (!StringUtils.hasText(value)) {
            return value;
        }

        // 如果全局脱敏被禁用，直接返回原值
        if (!properties.isSensitiveEnabled()) {
            return value;
        }

        // 评估条件表达式
        if (!conditionEvaluator.evaluate(annotation.condition())) {
            return value;
        }

        // 获取脱敏策略并执行脱敏
        SensitiveStrategy strategy = strategyFactory.getStrategy(annotation.strategy());
        return strategy.desensitize(value, annotation.params());
    }
}